import { createStore } from 'vuex'
import { App } from 'vue'
import VueNativeSock from 'vue-native-websocket-vue3'

const SOCKET_ONOPEN = '✅ Socket connected!'
const SOCKET_ONCLOSE = '❌ Socket disconnected!'
const SOCKET_ONERROR = '❌ Socket Error!!!'
const SOCKET_ONMESSAGE = 'Websocket message received'
const SOCKET_RECONNECT = 'Websocket reconnected'
const SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..'

const store = createStore({
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false
    }
  },
  mutations: {
    [SOCKET_ONOPEN](state) {
      state.socket.isConnected = true
    },
    [SOCKET_ONCLOSE](state) {
      state.socket.isConnected = false
    },
    [SOCKET_ONERROR](state, event) {
      console.error(state, event)
    },
    [SOCKET_ONMESSAGE](state, message) {
      console.log(message)
      state.socket.message = message
    },
    [SOCKET_RECONNECT](state, count) {
      console.info(state, count)
    },
    [SOCKET_RECONNECT_ERROR](state) {
      state.socket.reconnectError = true
    }
  }
})

const mutations = {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
}

export default (app: App): void => {
  app.use(VueNativeSock, ' ', {
    store,
    mutations,
    connectManually: true,
    format: 'json'
  })
}
